package network;

import java.io.IOException;
import java.net.Socket;

import network.server.ClientList;

/**
 * Message Dispatcher is used to send messages over the network. It provides
 * functionality to send a message to one client or to all the clients who are
 * currently connected to the server.
 * 
 * @author Jie Zhao(288654)
 * 
 */
public class MessageDispatcher {
	private MessageDispatcher() {
	}

	/**
	 * Dispatch a message to a client.
	 * 
	 * @param s
	 * @param msg
	 * @throws IOException
	 */
	public static void dispatch(Socket s, Message msg) throws IOException {
		if (s == null || msg == null)
			return;
		try {
			s.getOutputStream().write(msg.toByteArray());
			s.getOutputStream().flush();
		} catch (IOException e) {
			throw e;
		}
	}

	/**
	 * dispatch a message to all the clients
	 * 
	 * @param msg
	 */
	public static void dispatchToAll(Message msg) {
		if (msg == null)
			return;
		for (Client c : ClientList.getInstance().getClientList()) {
			try {
				Socket s = c.getClientSocket();
				if (s != null && s.isConnected() && !s.isClosed()) {
					s.getOutputStream().write(msg.toByteArray());
					s.getOutputStream().flush();
				}
			} catch (Exception e) {
			}
		}
	}

}
